import random
import json
import os

class QuestionBank:
    def __init__(self):
        self.bank_dir = "D:/学生算题系统2/data/question_bank"
        self.bank_file = os.path.join(self.bank_dir, "questions.json")
        self.questions = []
        self.load_bank()
    
    def load_bank(self):
        """加载题库"""
        os.makedirs(self.bank_dir, exist_ok=True)
        
        if os.path.exists(self.bank_file):
            with open(self.bank_file, 'r', encoding='utf-8') as f:
                self.questions = json.load(f)
        else:
            # 如果题库不存在，初始化一个基础题库
            self._initialize_bank()
    
    def save_bank(self):
        """保存题库"""
        os.makedirs(self.bank_dir, exist_ok=True)
        with open(self.bank_file, 'w', encoding='utf-8') as f:
            json.dump(self.questions, f, ensure_ascii=False, indent=2)
    
    def _initialize_bank(self):
        """初始化题库，生成基础的加减法题目"""
        # 生成100道加法题
        for _ in range(100):
            num2 = random.randint(1, 99)
            num1 = random.randint(1, 100 - num2)
            question = {
                'question': f"{num1} + {num2} = ",
                'answer': str(num1 + num2),
                'type': 'addition'
            }
            self.questions.append(question)
        
        # 生成100道减法题
        for _ in range(100):
            num1 = random.randint(1, 99)
            num2 = random.randint(0, num1)
            question = {
                'question': f"{num1} - {num2} = ",
                'answer': str(num1 - num2),
                'type': 'subtraction'
            }
            self.questions.append(question)
        
        self.save_bank()
    
    def add_question(self, question, answer, type_):
        """添加新题目到题库"""
        new_question = {
            'question': question,
            'answer': str(answer),
            'type': type_
        }
        self.questions.append(new_question)
        self.save_bank()
    
    def get_random_questions(self, count=50):
        """从题库中随机获取指定数量的题目"""
        if count > len(self.questions):
            raise Exception("题库中的题目数量不足")
        return random.sample(self.questions, count)
    
    def get_questions_by_type(self, type_, count):
        """获取指定类型的随机题目"""
        type_questions = [q for q in self.questions if q['type'] == type_]
        if count > len(type_questions):
            raise Exception(f"题库中{type_}类型的题目数量不足")
        return random.sample(type_questions, count) 